import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../fluttergromore/ads/ads_utils.dart';

// 食物记录数据模型
class FoodRecord {
  final String foodName;
  final double protein; // 蛋白质(g)
  final double carbs;   // 碳水(g)
  final double fat;     // 脂肪(g)
  final String mealType; // 餐次类型：早餐、午餐、晚餐、零食
  final DateTime timestamp;
  
  // 计算卡路里：蛋白质×4 + 碳水×4 + 脂肪×9
  double get calories => protein * 4 + carbs * 4 + fat * 9;

  FoodRecord({
    required this.foodName,
    required this.protein,
    required this.carbs,
    required this.fat,
    required this.mealType,
    required this.timestamp,
  });

  // 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'foodName': foodName,
      'protein': protein,
      'carbs': carbs,
      'fat': fat,
      'mealType': mealType,
      'timestamp': timestamp.toIso8601String(),
    };
  }

  // 从JSON创建
  factory FoodRecord.fromJson(Map<String, dynamic> json) {
    return FoodRecord(
      foodName: json['foodName'],
      protein: json['protein'].toDouble(),
      carbs: json['carbs'].toDouble(),
      fat: json['fat'].toDouble(),
      mealType: json['mealType'],
      timestamp: DateTime.parse(json['timestamp']),
    );
  }
}

class ReliangLogic extends GetxController {
  // 食物记录列表
  var foodRecords = <FoodRecord>[].obs;
  
  // 总计营养素
  var totalCalories = 0.0.obs;
  var totalProtein = 0.0.obs;
  var totalCarbs = 0.0.obs;
  var totalFat = 0.0.obs;

  // 输入表单控制器
  final foodNameController = TextEditingController();
  final proteinController = TextEditingController();
  final carbsController = TextEditingController();
  final fatController = TextEditingController();
  final notesController = TextEditingController();

  // 当前选择的餐次类型
  var selectedMealType = ''.obs;

  @override
  void onInit() {
    super.onInit();
    loadTodayRecords();
  }

  @override
  void onClose() {
    // 清理控制器
    foodNameController.dispose();
    proteinController.dispose();
    carbsController.dispose();
    fatController.dispose();
    notesController.dispose();
    super.onClose();
  }

  // 加载今日记录
  Future<void> loadTodayRecords() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final todayKey = _getTodayKey();
      final recordsJson = prefs.getString(todayKey);
      
      if (recordsJson != null) {
        final List<dynamic> recordsList = json.decode(recordsJson);
        foodRecords.value = recordsList
            .map((json) => FoodRecord.fromJson(json))
            .toList();
      } else {
        foodRecords.clear();
      }
      
      _updateTotals();
    } catch (e) {
      Get.snackbar('错误', '加载记录失败：${e.toString()}');
    }
  }

  // 显示食物输入对话框
  void showFoodInputDialog(String mealType) {

    AdsUtils.showInterstitialAd();

    selectedMealType.value = mealType;
    
    // 清空输入框
    foodNameController.clear();
    proteinController.clear();
    carbsController.clear();
    fatController.clear();
    notesController.clear();

    Get.dialog(
      AlertDialog(
        title: Text('添加$mealType'),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: foodNameController,
                decoration: const InputDecoration(
                  labelText: '食物名称',
                  hintText: '请输入食物名称',
                ),
              ),
              const SizedBox(height: 8),
              TextField(
                controller: proteinController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '蛋白质含量 (g)',
                  hintText: '0',
                ),
              ),
              const SizedBox(height: 8),
              TextField(
                controller: carbsController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '碳水化合物含量 (g)',
                  hintText: '0',
                ),
              ),
              const SizedBox(height: 8),
              TextField(
                controller: fatController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '脂肪含量 (g)',
                  hintText: '0',
                ),
              ),
              const SizedBox(height: 8),
              TextField(
                controller: notesController,
                decoration: const InputDecoration(
                  labelText: '备注 (可选)',
                  hintText: '添加备注信息',
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: _addFoodRecord,
            child: const Text('确认'),
          ),
        ],
      ),
    );
  }

  // 添加食物记录
  Future<void> _addFoodRecord() async {
    try {
      // 输入验证
      if (foodNameController.text.trim().isEmpty) {
        Get.snackbar('提示', '请输入食物名称');
        return;
      }

      final protein = double.tryParse(proteinController.text) ?? 0.0;
      final carbs = double.tryParse(carbsController.text) ?? 0.0;
      final fat = double.tryParse(fatController.text) ?? 0.0;

      if (protein < 0 || carbs < 0 || fat < 0) {
        Get.snackbar('提示', '营养素含量不能为负数');
        return;
      }

      if (protein == 0 && carbs == 0 && fat == 0) {
        Get.snackbar('提示', '请至少输入一种营养素含量');
        return;
      }

      // 创建新记录
      final newRecord = FoodRecord(
        foodName: foodNameController.text.trim(),
        protein: protein,
        carbs: carbs,
        fat: fat,
        mealType: selectedMealType.value,
        timestamp: DateTime.now(),
      );

      // 添加到列表
      foodRecords.add(newRecord);
      
      // 保存到本地
      await _saveRecords();
      
      // 更新总计
      _updateTotals();
      
      // 关闭对话框
      Get.back();
      
      Get.snackbar('成功', '食物记录已添加');
    } catch (e) {
      Get.snackbar('错误', '添加记录失败：${e.toString()}');
    }
  }

  // 删除食物记录
  Future<void> deleteFoodRecord(int index) async {
    try {
      foodRecords.removeAt(index);
      await _saveRecords();
      _updateTotals();
      Get.snackbar('成功', '记录已删除');
    } catch (e) {
      Get.snackbar('错误', '删除记录失败：${e.toString()}');
    }
  }

  // 保存记录到本地存储
  Future<void> _saveRecords() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final todayKey = _getTodayKey();
      
      if (foodRecords.isEmpty) {
        await prefs.remove(todayKey);
      } else {
        final recordsJson = json.encode(
          foodRecords.map((record) => record.toJson()).toList(),
        );
        await prefs.setString(todayKey, recordsJson);
      }
    } catch (e) {
      throw Exception('保存记录失败：${e.toString()}');
    }
  }

  // 更新总计营养素
  void _updateTotals() {
    totalCalories.value = 0.0;
    totalProtein.value = 0.0;
    totalCarbs.value = 0.0;
    totalFat.value = 0.0;

    for (final record in foodRecords) {
      totalCalories.value += record.calories;
      totalProtein.value += record.protein;
      totalCarbs.value += record.carbs;
      totalFat.value += record.fat;
    }
  }

  // 获取今日存储键
  String _getTodayKey() {
    final now = DateTime.now();
    return 'calorie_records_${now.year}_${now.month}_${now.day}';
  }
}